import React from "react";
import { Toast } from "antd-mobile";
import ReactPullLoad, { STATS } from "react-pullload";
import "../../../../node_modules/react-pullload/dist/ReactPullLoad.css";
import wx from "weixin-js-sdk";

export default class Index extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      toMax: false,
      id: props.match.params.id,
      hasMore: true,
      data: [],
      action: STATS.init,
      page: 1,
      sort: 1, //1--正序  2--倒序
      z_price: 0,
      is_pay: 0,
      is_free: 0,
      sharebg: false,
    };
  }
  componentDidMount() {
    document.title = "详情";
    this.getData();

    global.Ajax.hhtc_request("user/get_qrcode", {}).then((data) => {
      console.log("第一步 ", data);
      if (data.code === 1) {
        this.setState(data.data);
      }
    });

    global.Ajax.hhtc_request("web/get_share", {
      windowurl: window.location.href,
    }).then((data) => {
      console.log("分享页面的数据 ", data);
      if (data.code === 1) {
        wx.config({
          debug: false,
          appId: data.data.appId,
          timestamp: data.data.timestamp,
          nonceStr: data.data.noncestr,
          signature: data.data.signature,
          jsApiList: [
            // 所有要调用的 API 都要加到这个列表中
            "updateTimelineShareData", //分享给好友
            "updateAppMessageShareData", //分享到朋友圈
          ],
        });

        wx.checkJsApi({
          jsApiList: ["updateTimelineShareData", "updateAppMessageShareData"], // 需要检测的JS接口列表，所有JS接口列表见附录2,
          success: function (res) {
            console.log("checkJsApi--", res);
            // 以键值对的形式返回，可用的api值true，不可用为false
            // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
          },
        });
        wx.error(function (res) {
          console.log(res);
          // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
        });

        wx.ready(() => {
          //配置好需要分享的几个配置，这里只是演示，实际开发中应该是动态的变量
          var shareData = {
            title: "好友邀请你加入艺看学院",
            desc: "你的好友正在邀请你加入艺看学院，快来看看吧",
            link: window.location.href.split("#")[0],
            imgUrl:
              "https://yksy.qianjitianxia.com/o_1eiao12gcfa6122j1eicun0pjl8.png", //传递给微信需传递完整的带url链接
            success: function () {
              global.Ajax.hhtc_request("user/share", {}).then((data) => {
                console.log("data: ", data);
                // return Toast.success(data.msg);
              });
            },
          };

          //调用各个接口并传入配置变量
          wx.updateTimelineShareData(shareData);
          wx.updateAppMessageShareData(shareData);
        });
      }
    });
  }
  getData() {
    global.Ajax.hhtc_request("product/detail", { id: this.state.id }).then(
      (data) => {
        console.log("data: ", data);
        if (data.code === 1) {
          this.setState(data.data);
          this.setState({
            // sort: data.data.type,
            is_pay: data.data.is_pay,
            is_free: data.data.is_free,
          });
          this.getList();
        }
      }
    );
  }
  getList() {
    var req = {
      page: 1,
      size: 12,
      id: this.state.id,
      type: this.state.sort,
    };
    global.Ajax.hhtc_request("product/content_list", req).then((data) => {
      if (data.code === 1) {
        var hasMore;
        if (data.data.length > 0) {
          this.state.page++;
          hasMore = true;
        } else {
          hasMore = false;
        }
        this.setState({
          data: data.data.data,
          hasMore: hasMore,
          page: this.state.page,
        });
      }
    });
  }
  // 获取商品
  handleAction = (action) => {
    console.info(action, this.state.action, action === this.state.action);
    //new action must do not equel to old action
    if (action === this.state.action) {
      return false;
    }
    if (action === STATS.refreshing) {
      //刷新
      this.handRefreshing();
    } else if (action === STATS.loading) {
      //加载更多
      this.handLoadMore();
    } else {
      //DO NOT modify below code
      this.setState({
        action: action,
      });
    }
  };
  handRefreshing = () => {
    if (STATS.refreshing === this.state.action) {
      return false;
    }
    var req = {
      page: 1,
      size: 12,
      id: this.state.id,
      type: this.state.sort,
    };
    global.Ajax.hhtc_request("product/content_list", req).then((data) => {
      if (data.code === 1) {
        var hasMore;
        if (data.data.length > 0) {
          this.state.page++;
          hasMore = true;
        } else {
          hasMore = false;
        }
        this.setState({
          data: data.data.data,
          hasMore: hasMore,
          action: STATS.refreshed,
          page: this.state.page,
        });
      }
    });
    this.setState({
      action: STATS.refreshing,
    });
  };
  handLoadMore = () => {
    if (STATS.loading === this.state.action) {
      return false;
    }
    //无更多内容则不执行后面逻辑
    if (!this.state.hasMore) {
      return;
    }
    var req = {
      page: this.state.page,
      size: 12,
      id: this.state.id,
      type: this.state.sort,
    };
    global.Ajax.hhtc_request("product/content_list", req).then((data) => {
      if (data.code === 1) {
        if (data.data.length > 0) {
          this.setState({
            data: this.state.data.concat(data.data.data),
            action: STATS.reset,
          });
        } else {
          this.setState({
            action: STATS.reset,
            hasMore: false,
          });
        }
      }
    });
    this.setState({
      action: STATS.loading,
    });
  };
  // 排序
  sort() {
    var sort;
    if (this.state.toMax) {
      sort = 1;
    } else {
      sort = 2;
    }
    this.setState(
      {
        toMax: !this.state.toMax,
        page: 1,
        sort: sort,
      },
      () => {
        this.getList();
      }
    );
  }
  // 加入书架
  join_book() {
    global.Ajax.hhtc_request("product/add_bookcase", {
      id: this.state.id,
    }).then((data) => {
      if (data.code === 1) {
        Toast.success(data.msg, 1, () => {
          this.getData();
        });
      } else {
        Toast.fail(data.msg, 1);
      }
    });
  }
  // 购买课程
  buy() {
    this.props.history.push("/page/home/learn/Order/" + this.state.id);
  }
  render() {
    return (
      <div className='learn_detail_box'>
        <div className='detail'>
          <img alt='' src={this.state.img} className='pic' />
          <div className='right'>
            <p className='title' style={{ paddingTop: "2px" }}>
              {this.state.title}
            </p>
            <div className='flex'>
              <p className='writer'>{this.state.author}</p>
              <div className='btnbox'>
                {this.state.is_bookcase === 1 ? (
                  <div onClick={this.join_book.bind(this)}>
                    <img
                      alt=''
                      src={require("../../imgs/book2.png")}
                      className='icon'
                    />
                    <p>已加入</p>
                  </div>
                ) : (
                  <div onClick={this.join_book.bind(this)}>
                    <img
                      alt=''
                      src={require("../../imgs/book1.png")}
                      className='icon'
                    />
                    <p>加入书架</p>
                  </div>
                )}

                <div>
                  <img
                    alt=''
                    src={require("../../imgs/shareicon.png")}
                    className='icon'
                  />
                  <p
                    onClick={() => {
                      this.setState({
                        sharebg: true,
                      });
                    }}
                  >
                    分享
                  </p>
                </div>
              </div>
            </div>
            <p className='ms'>{this.state.info}</p>
            <div className='scbox'>
              <img
                alt=''
                src={require("../../imgs/head.png")}
                className='head'
              />
              <p>上传：官方账户</p>
            </div>
          </div>
        </div>
        <ReactPullLoad
          downEnough={100}
          action={this.state.action}
          handleAction={this.handleAction}
          hasMore={this.state.hasMore}
          distanceBottom={100}
        >
          <div className=''>
            <h1 className='nrtitle'>内容介绍</h1>
            <p className='desc' style={{ height: "auto", display: "block" }}>
              {this.state.content}
            </p>
            {this.state.is_jiang === 1 && (
              <div className='giftbox'>
                <img
                  alt=''
                  src={require("../../imgs/gift.png")}
                  className='gift_icon'
                />
                <p className='zi'>
                  分享{this.state.tj_num}位好友可获得积分奖励~
                </p>
                <p className='sharebtn'>立即分享</p>
              </div>
            )}
            <div className='mlbox'>
              <h1>目录</h1>
              {this.state.toMax ? (
                <img
                  alt=''
                  src={require("../../imgs/ml.png")}
                  className='ml'
                  onClick={this.sort.bind(this)}
                />
              ) : (
                <img
                  alt=''
                  src={require("../../imgs/ml1.png")}
                  className='ml'
                  onClick={this.sort.bind(this)}
                />
              )}
              <p>共{this.state.data.length}章</p>
            </div>
            <div className='list'>
              {this.state.data.map((item, index) => {
                return (
                  <div
                    key={"list" + index}
                    className='item'
                    onClick={() => {
                      if (this.state.type === 1) {
                        //视频
                        if (this.state.is_pay == 1 || item.is_shiting == 1) {
                          this.props.history.push(
                            "/page/home/learn/video/" +
                              item.id +
                              "/" +
                              this.state.sort
                          );
                        } else {
                          return Toast.info("请先购买");
                        }
                      } else {
                        //音频
                        if (this.state.is_pay == 1 || item.is_shiting == 1) {
                          this.props.history.push(
                            "/page/home/learn/audio/" +
                              item.id +
                              "/" +
                              this.state.sort
                          );
                        } else {
                          return Toast.info("请先购买");
                        }
                      }
                    }}
                  >
                    <p className='num'>{index + 1}</p>
                    <div className='right'>
                      <div className='topbox'>
                        {item.is_shiting === 1 && <p className='shiy'>试听</p>}
                        <h2>{item.title}</h2>
                        <span>{item.atime}</span>
                      </div>
                      <div className='bofbox'>
                        <div className='play'>
                          <img alt='' src={require("../../imgs/play.png")} />
                          <p>{item.k_num}</p>
                        </div>
                        <div>
                          <img alt='' src={require("../../imgs/time.png")} />
                          <p>{item.time}</p>
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}

              {/* <div className='item' onClick={()=>{}}>
                                <p className='num'>2</p>
                                <div className='right'>
                                    <div className='topbox'>
                                        <h2>梅泰罗的成长历程，说话的魅力所在</h2>
                                        <span>2020-02-12</span>
                                    </div>
                                    <div className='bofbox'>
                                        <div className='play'>
                                            <img alt='' src={require('../../imgs/play.png')} />
                                            <p>1.5万</p>
                                        </div>
                                        <div>
                                            <img alt='' src={require('../../imgs/time.png')} />
                                            <p>03:29</p>
                                        </div>
                                    </div>
                                </div>
                            </div> */}
            </div>
          </div>
        </ReactPullLoad>
        {this.state.is_pay === 0 && (
          <div className='bott'>
            {/* <p>购买课程</p>
                    <h1>99.99元</h1>
                    <span>再邀请5位好友免费学</span> */}
            {this.state.is_free === 2 && (
              <h2 onClick={this.buy.bind(this)}>
                购买课程<span>{this.state.z_price * 1}元</span>
              </h2>
            )}
            {this.state.is_free === 3 && (
              <h2 onClick={this.buy.bind(this)}>
                购买课程<span>{this.state.z_price * 1}</span>
                <img
                  alt=''
                  src={require("../../imgs/hua.png")}
                  style={{ width: 14, height: 19, marginLeft: "5px" }}
                />
              </h2>
            )}
            {this.state.is_free === 4 && (
              <h2 onClick={this.buy.bind(this)}>
                购买课程<span>{this.state.z_price * 1}</span>
                <img
                  alt=''
                  src={require("../../imgs/999.png")}
                  style={{ width: 14, height: 19, marginLeft: "5px" }}
                />
              </h2>
            )}
          </div>
        )}
      </div>
    );
  }
}
